package 外观数列;

class Solution {
    public String countAndSay(int n) {
        if(n == 1){
            return "1";
        }
        String tmp = countAndSay(n - 1);
        return func(tmp);    
    }

    //暴力循环
    public String func(String tmp){
        StringBuilder str = new StringBuilder();
        if(tmp.length() == 1){
            str.append(1);
            str.append(tmp);
            return str.toString();
        }
        int n = tmp.length();
        for (int i = 0; i < n; i++){
            int count = 1;
            while (i < n && tmp.charAt(i+1) == tmp.charAt(i)){
                count++;
                i++;
            }
            str.append(count);
            str.append(tmp.charAt(i));
        }
        return str.toString();
    }

    //双指针
    public String func2(String tmp){
        StringBuilder str = new StringBuilder();
        int n = tmp.length();
        int left = 0;
        int right = 0;
        while (right < n){
            while (right < n && tmp.charAt(right) == tmp.charAt(left)){
                right++;
            }
            str.append(right - left);
            str.append(tmp.charAt(left));
            left = right;
        }
        return str.toString();
    }
}